<template>
  <div class="equipment-manage-add-page">
    <div class="page-title-container flex" :title="pageTtile">
      <a-button type="default" @click="back()">返回 </a-button>
    </div>
    <div class="page-body-container">
      <!-- 顶部查询条件 -->
      <div class="conditions-warp">
        <a-row>
          <a-form-model ref="ruleForm" :model="conditions" :rules="rules">
            <!-- 项目名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item ref="proName" label="项目名称" prop="proName">
                <a-select
                  v-model="commonField.tenantName"
                  placeholder="请选择项目名称"
                  disabled
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 标段名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item
                ref="blockName"
                label="标段名称"
                prop="blockName"
              >
                <a-select
                  v-model="commonField.secName"
                  placeholder="请选择标段名称"
                  disabled
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 角色名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="12">
              <a-form-model-item
                ref="roleName"
                label="角色名称"
                prop="roleName"
              >
                <a-select
                  mode="multiple"
                  v-model="conditions.roleName"
                  placeholder="请选择角色名称"
                >
                  <a-select-option
                    :value="item.id"
                    v-for="item in conditions.roleNameSource"
                    :key="item.id"
                  >
                    {{ item.roleName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 系统名称 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item ref="sysName" label="系统名称" prop="sysName">
                <a-select
                  v-model="commonField.systemName"
                  placeholder="请选择系统名称"
                  disabled
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 设备类型 -->
            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="6">
              <a-form-model-item ref="equType" label="设备类型" prop="equType">
                <a-select
                  v-model="commonField.equTypeDesc"
                  placeholder="请选择设备类型"
                  disabled
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <!-- 试验室名称 -->
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="12"
              :xl="12"
              :xxl="6"
              v-if="systemCode == 'SYGLXT'"
            >
              <a-form-model-item
                ref="testName"
                label="试验室名称"
                prop="testName"
              >
                <a-select
                  v-model="commonField.trialRoomName"
                  placeholder="请选择试验室名称"
                  disabled
                >
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </a-row>
      </div>
      <!--  -->
      <div class="equment-list-card-container">
        <addEquCard
          :simple="true"
          :title="commonField.equTypeDesc"
          id="id_0"
          ref="addEquCard"
          :fieldSource="fieldSource"
          :isShowDelete="false"
        ></addEquCard>
      </div>
      <!-- 提交按钮 -->
      <div class="footer">
        <a-button @click="back()"> 取消 </a-button>
        <a-button
          :loading="submitLoading"
          type="primary"
          style="margin-left: 10px"
          :disabled="fieldSource.length == 0"
          @click="onSubmit()"
        >
          确定
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
//【编辑】页面
import addEquCard from "./components/addEquCard";
import {
  getByCondition,
  editorEquiment,
  queryEquimentDetails,
} from "@/api/user-center/equipmentManage.js";
import { getUserRole } from "@/api/user-center/userManage.js";
import { getLoginData } from "@/tools";
export default {
  components: { addEquCard },
  data() {
    return {
      pageTtile: "编辑",
      operate: 0,
      conditions: {
        //项目名称
        proNameSource: [],
        proName: undefined,
        proNameLoading: true,
        //标段名称
        blockNameSource: [],
        blockName: undefined,
        blockLoading: false,
        //角色名称
        roleNameSource: [],
        roleName: undefined,
        roleLoading: false,
        //系统名称
        sysNameSource: [],
        sysName: undefined,
        sysNameLoading: false,
        //设备类型
        equTypeSource: [],
        equType: undefined,
        equTypeLoading: false,
        //实验室名称
        testNameLoading: false,
        testNameSource: [],
        testName: undefined,
      },
      rules: {
        roleName: [
          { required: true, message: "请选择角色名称", trigger: "change" },
        ],
      },
      fieldSource: [],
      equimentList: [],
      equimentParams: {},
      commonField: {},
      submitLoading: false,
      systemCode: "",
    };
  },
  mounted() {
    let { systemCode } = this.$route.query;
    this.systemCode = systemCode;
    this.queryEquimentDetails();
  },
  methods: {
    //查询数据详情
    queryEquimentDetails() {
      let { id = "" } = this.$route.query;
      return new Promise((resolve, reject) => {
        queryEquimentDetails({ id })
          .then(async (res) => {
            let { data } = res;
            this.fieldSource = data?.result?.specialField || [];
            this.commonField = data?.result?.commonField || {};
            if (this.commonField?.secCode) {
              let aa = await this.getRoleList(
                this.commonField?.secCode || ""
              ).finally((_) => {});
            }
            resolve();
          })
          .catch((_) => {
            this.commonField = {};
            this.fieldSource = [];
            reject();
          });
      });
    },

    //提交
    onSubmit() {
      let { fieldSource } = this;
      if (fieldSource.length == 0) {
        return this.$message.warn("最少添加一条数据");
      }

      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          try {
            let ref = this.$refs["addEquCard"];
            if (ref) {
              ref
                .dataValidate()
                .then((res) => {
                  let { form = {} } = res;
                  Object.keys(form).forEach((key) => {
                    if (form[key] == undefined) {
                      form[key] = "";
                    }
                  });
                  this.equimentParams = form;
                  this.confirmAddEquiment();
                })
                .catch((_) => {
                  let { title } = _;
                  this.$message.error(`【${title}】数据填写不完整`);
                  throw _;
                });
            }
          } catch (error) {}
        } else {
          let { roleName } = this.conditions;
          if (!roleName || roleName.length == 0) {
            this.$message.warn("请选择角色名称");
          }
          return false;
        }
      });
    },

    //确定
    confirmAddEquiment() {
      this.submitLoading = true;
      let { roleName = [] } = this.conditions;
      let { commonField } = this;
      if (!this.equimentParams.long || !this.equimentParams.lat) {
        this.equimentParams.location = ``;
      } else {
        this.equimentParams.location = `${this.equimentParams.long},${this.equimentParams.lat}`;
      }
      this.equimentParams.tenantCode = commonField.tenantCode || "";
      this.equimentParams.orgCode = commonField.secCode || "";
      this.equimentParams.systemCode = commonField.systemCode || "";
      this.equimentParams.systemCode = commonField.systemCode || "";
      this.equimentParams.equTypeValue = commonField.equTypeValue || "";
      this.equimentParams.roleIds = roleName.toString();
      this.equimentParams.id = this.$route.query?.id;
      editorEquiment(this.equimentParams)
        .then((res) => {
          this.$message.success("操作成功");
          this.back();
        })
        .catch((_) => {
          this.$message.error("操作失败，请稍后重试！");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //查询设备字段列表
    getByCondition() {
      return new Promise((resolve, reject) => {
        let { proName, blockName, sysName, equType } = this.conditions;
        getByCondition({
          tenantCode: proName || "",
          secCode: blockName || "",
          systemCode: sysName || "",
          equTypeValue: equType || "",
        })
          .then((res) => {
            let { data } = res;
            this.fieldSource = data?.result || [];
            //默认添加一个设备
            if (this.fieldSource.length > 0) {
              this.equimentList = [{}];
            }
          })
          .catch((_) => {
            this.fieldSource = [];
          });
      });
    },

    //【查询条件】监听查询条件切换
    conditionChange(ev, keyName) {
      this.conditions[keyName] = ev;
      switch (keyName) {
        case "proName":
          this.conditions.blockName = undefined;
          this.conditions.sysName = undefined;
          this.conditions.equType = undefined;
          this.conditions.blockNameSource = [];
          this.conditions.sysNameSource = [];
          this.conditions.equTypeSource = [];
          this.getBlockList(ev || "");
          this.getSystemList(ev || "");
          this.getEquTypeList(ev || "");
          break;

        case "blockName":
          this.getRoleList(ev || "");
          break;

        case "sysName":
          this.conditions.equType = undefined;
          this.conditions.equTypeSource = [];
          this.getEquTypeList(ev || "");
          break;

        case "equType":
          this.getByCondition();
          break;

        default:
          break;
      }
    },

    //【查询条件】查询角色下拉框
    getRoleList(orgCode = "") {
      this.conditions.roleLoading = true;
      let { tenantCode, secCode } = this.$route.query;
      return new Promise((resolve, reject) => {
        getUserRole({ tenantCode, orgCode })
          .then((res) => {
            let { data } = res;
            this.conditions.roleNameSource = data?.result || [];
            setTimeout((_) => {
              let ids = (this.commonField.roleId || "").split(",");
              this.conditions.roleName = ids;
            }, 0);
            resolve();
          })
          .catch((_) => {
            this.conditions.roleNameSource = [];
            reject();
          })
          .finally((_) => {
            this.conditions.roleLoading = false;
          });
      });
    },

    //获取设备名称
    getEqumentName() {
      let { equTypeSource, equType = "" } = this.conditions;
      if (equType) {
        return equTypeSource.find((v) => v.dicValue == equType)?.dicDesc || "";
      } else {
        return "";
      }
    },

    //返回
    back() {
      this.$router.back();
    },
  },
};
</script>

<style lang="less">
.equipment-manage-add-page {
  height: 100%;
  .flex();
  flex-direction: column;
  box-sizing: border-box;
  padding: 0 0 0 10px;
  .page-title-container {
    height: 46px;
    background: #ffffff;
    justify-content: space-between;
    padding: 0 20px;
    align-items: center;
    border-bottom: 1px solid #e8ebf0;
    &::before {
      .flex();
      align-items: center;
      content: attr(title);
      font-size: 16px;
      height: 16px;
      border-left: 3px solid var(--primary-color);
      padding-left: 10px;
    }
  }
  .page-body-container {
    flex: 1;
    flex-wrap: wrap;
    background: #fff;
    .custom-scrollbar();
    .conditions-warp {
      padding: 30px 100px 0 10px;
      .ant-form-item {
        .flex();
        .ant-form-item-label {
          width: 120px;
          flex-shrink: 0;
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          textarea {
            height: 80px;
          }
          .ant-calendar-picker {
            width: 100%;
          }
        }
      }
      /deep/.ant-select {
        width: 100%;
      }
    }
    .equment-list-card-container {
      padding: 0 32px;
    }

    .footer {
      height: 72px;
      border-top: 1px solid #f3f4f6;
      margin-top: 34px;
      .flex();
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
